package com.watchthelan.service.administrator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.watchthelan.domain.Administrator;
import com.watchthelan.domain.AdministratorPassword;

public class AdministratorPasswordValidator implements Validator {
	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class arg0) {
		return AdministratorPassword.class.equals(arg0);
	}

	@Override
	public void validate(Object arg0, Errors errors) {
		AdministratorPassword aPassword = (AdministratorPassword) arg0;
		ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"../applicationContext.xml"});
		AdministratorManager administratorManager = (AdministratorManager) ctx.getBean("administratorManager");
		
		//get administrator for this password
		Administrator administrator = administratorManager.getAdministratorById(new Long(aPassword.getAdministratorId()));
		if (administrator == null) {
			errors.rejectValue("oldPassword", "error.administrator.does_not_exist");
			return;
		}
		
		//check oldPassword only if the administrator already had a password
		if (administrator.getPassword() != null) {
			logger.info("administrator password was set before");
			if ("".equals(aPassword.getOldPassword())) {
				errors.rejectValue("oldPassword", "error.password.old.missing", null, "Value required.");
			}
			if (!administrator.getPassword().equals(aPassword.getOldPassword())) {
				errors.rejectValue("oldPassword", "error.password.old.does_not_match", null, "Value required.");
			}
		}

		//verify newPassword equals confirmPassword
		if ((aPassword.getNewPassword() != null) 
				&& !aPassword.getNewPassword().equals(aPassword.getConfirmPassword())) {
			logger.info("administrator newpassword not null");
			if ("".equals(aPassword.getConfirmPassword())) {
				errors.rejectValue("confirmPassword", "error.password.confirm.missing", null, "Value required.");
			} else {
				errors.rejectValue("confirmPassword", "error.password.does_not_match", null, "Value required.");
			}
		}
		if (aPassword.getNewPassword() == null) {
			logger.info("new password is null");
			errors.rejectValue("newPassword", "error.password.new.missing", null, "Value required.");
		}

		//verify password against internal rules
		// TODO:
	}

}
